<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BaseController extends Controller
{
    //
    /**
     *返回格式
     * @param int $error_code
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return \Illuminate\Http\JsonResponse
     */
    public function witejson($error_code=0,$data=[],$msg='',$code=200)
    {
        return response()->json([
            'error_code'=>$error_code,
            'data'=>$data,
            'msg'=>$msg
        ],$code);
    }

    /**
     * 子集递归
     * @param $data
     * @param int $pid
     * @return array
     */
    public function sonlevel($data,$pid=0)
    {
        $arr = [];
        foreach ($data as $key=>$val){
            if($val['pid'] == $pid){
                $val['son'] = $this->sonlevel($data,$val['id']);
                $arr[] = $val;
            }
        }
        return $arr;
    }


    /**
     * 递归
     * @param $data 传入的参数
     * @param int $pid 父级id
     * @param string $html 添加的分隔符
     * @param int $level  层级
     */
    public function treelevel($data,$pid=0,$html='--',$level=0)
    {
        static $arr = [];//定义静态数组 所以无法覆盖
        foreach ($data as $val){
            if($val['pid'] == $pid){
                $val['html'] = str_repeat($html,$level*2);
                $val['level'] = $level+1;
                $arr[] = $val;
                $this->treelevel($data,$val['id'],$html,$val['level']);
            }
        }
        return $arr;
    }

}
